//
//  MoreNewsViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 2/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MoreNewsViewController.h"
#import "MoreNewsTableCell.h"
#import "ZHDataService.h"
#import "ZHWebService.h"
#import "ActivityViewManager.h"
#import "MoreButtonCell.h"
#import "WDNews.h"
#import "UIImageView+LoadImagesFromInternet.h"
#import "DetailViewController.h"
#import "HeaderView.h"
#import "WDFansAppDelegate.h"


const NSInteger firstPageIndex = 1;
static NSInteger nextPageIndex = 2;

@interface MoreNewsViewController()
- (void)moreButtonCicked;
- (void)callNetAndCallBackIsNextPage:(BOOL)isNext;
@end

@implementation MoreNewsViewController

//@synthesize myTableView;
@synthesize news = news_;
@synthesize currentPage = currentPage_;
@synthesize nextPageExist = nextPageExist_;
@synthesize detailControll;
@synthesize bar;
@synthesize isEditMode;

#pragma mark - own methods
- (void)callNetAndCallBackIsNextPage:(BOOL)isNext
{
    CompletionBlock completion = ^(NSData *data){
        self.currentPage = nextPageIndex;
        nextPageIndex++;
        NSDictionary *dict = [ZHDataService parseToNewesWithData:data];
        NSArray *newsArray = [dict objectForKey:@"recentNews"];
        NSString *anyPage = [NSString stringWithFormat:@"%@",[dict objectForKey:@"page"]];
        if(isNext)
            [self.news addObjectsFromArray:newsArray];
        else
            self.news = [NSMutableArray arrayWithArray:newsArray];
        if([anyPage isEqualToString:@"0"])
            self.nextPageExist = NO;
        else
            self.nextPageExist = YES;
        [self.myTableView reloadData];
    };
    ErrorBlock error = ^(NSString *error){
        //NSLog(@"get recent news:%@",error);
    };
    NSInteger requestPage;
    if(isNext)
        requestPage = nextPageIndex;
    else
        requestPage = firstPageIndex;
    [[ZHWebService sharedService] getRecentNewsWithPage:requestPage onCompletion:completion onError:error];
}

- (void)moreButtonCicked
{
    [self callNetAndCallBackIsNextPage:YES];
}

- (void)rightItemClicked
{
    //must be implemented in subclass
    [self callNetAndCallBackIsNextPage:NO];
}

- (IBAction)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - View lifecycle
- (void)dealloc
{
    
    detailControll.delegate = nil;
    [detailControll release];
    
    [bar release];
    [news_ release];
//    [myTableView release];
    [super dealloc];
}

- (id)initWithFirstPageNews:(NSArray *)firstPageNews andNextPage:(BOOL)nextPage
{
    self = [super initWithNibName:@"MoreNewsViewController" bundle:nil];
    if(self)
    {
        self.news = [NSMutableArray arrayWithArray:firstPageNews];
        self.nextPageExist = nextPage;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"新闻列表";
    self.currentPage = firstPageIndex;
//    [self setBackgroundImageViewForTabView];
//    [self addNaviBarRightRefreshItem];
    //[self moreButtonCicked];
    if (isEditMode==NO) {
        self.myTableView.editing = NO;
    }
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
 //   self.myTableView = nil;
    self.bar = nil;
}
#pragma -
#pragma mark - UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.nextPageExist)
        return 2;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return [self.news count];
    }
    return 1;
}

- (void)loadImage:(NSObject*)obj
{
    MoreNewsTableCell* cell = (MoreNewsTableCell*)obj;
    WDNews *news = [self.news objectAtIndex:cell.tag];
    
    NSURL *url = [NSURL URLWithString:news.newsImageUrl];
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    if(image!=nil)
    {
        news.newsCover = image;
        cell.coverImageView.image = image;
    }
    [image release];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        static NSString *cellIdentify = @"cellIdentify";
        MoreNewsTableCell *cell = (MoreNewsTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentify];
        if(cell == nil)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreNewsTableCell" owner:self options:nil];
            cell = (MoreNewsTableCell *)[nibs lastObject];
//            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        WDNews *news = [self.news objectAtIndex:indexPath.row];
        //coverImageView,newsDesLabel,newsDateLabel,newsNameLabel
        cell.newsNameLabel.text = news.newsTitle;
        cell.newsDesLabel.text = news.newsDescription;
        cell.newsDesLabel.frame = [cell.newsDesLabel textRectForBounds:cell.newsDesLabel.frame limitedToNumberOfLines:0];
        NSString *date = nil;
        if(news.newsDate != nil)
        {
            NSArray *ta = [news.newsDate componentsSeparatedByString:@" "];
            date = [ta objectAtIndex:0];
        }
        cell.newsDateLabel.text = date;
        
        cell.tag = indexPath.row;
//        if (news.newsCover==nil) {
//            [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:cell];
//        }
//        else {
//            cell.coverImageView.image = news.newsCover;
//        }
        
        [cell.coverImageView loadImageAsynchronousWithURL:news.newsImageUrl placeHolderImage:kNameOfDefaultNewsImage];
        return cell;
    }
    else
    {
        static NSString *cellIdentifyMore = @"cellIdentifyMore";
        MoreButtonCell *mbc = (MoreButtonCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifyMore];
        if(mbc == nil)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreButtonCell" owner:self options:nil];
            mbc = (MoreButtonCell *)[nibs lastObject];
        }
        return mbc;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
        return kTableCellHeight;
    else
        return kMoreButtonCellHeight;
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeaderViewHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:self options:nil];
        HeaderView *hv = (HeaderView *)[nibs lastObject];
        hv.titleLabel.text = [NSString stringWithFormat:@"当前共%d条新闻",[self.news count]];
        return hv;
    }
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        
        WDNews *selectedNews = [self.news objectAtIndex:indexPath.row];

        if (detailControll!=nil) {
            detailControll.delegate = nil;
            [detailControll release];
            detailControll = nil;
        }
        self.detailControll = [[Detail2ViewController alloc] initWithNews:selectedNews];
        detailControll.view.tag = 999999;
        detailControll.delegate = self;
        
        WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
        
        [appDelegate.window addSubview:detailControll.view];
        detailControll.view.frame = CGRectMake(320, 20, 320, 460);
        detailControll.view.alpha = 0.3;
        
        [UIView beginAnimations:@"" context:nil];
        [UIView setAnimationDelegate:nil];
        [UIView setAnimationDuration:0.25];
        detailControll.view.frame = CGRectMake(0, 20, 320, 460);
        detailControll.view.alpha = 1.0;
        [UIView commitAnimations];
        
    }
    else
    {
        [self moreButtonCicked];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (isEditMode==NO)
        return UITableViewCellEditingStyleNone;
    else {
        return UITableViewCellEditingStyleDelete;
    }
    
}


//– tableView:willBeginEditingRowAtIndexPath:
//– tableView:didEndEditingRowAtIndexPath:
//– tableView:editingStyleForRowAtIndexPath:
//– tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
//– tableView:shouldIndentWhileEditingRowAtIndexPath:




- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    
    NSString *filename=[path stringByAppendingPathComponent:@"WDNews"]; 
    NSData *fileData=[NSData dataWithContentsOfFile:filename];
    NSMutableArray* array = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
    
    [array removeObjectAtIndex:[indexPath row]];
    
    NSData *freezeDrid = [NSKeyedArchiver archivedDataWithRootObject:array];
    [freezeDrid writeToFile:filename atomically:YES];
    
    
    self.news = array;
    
    [tableView reloadData];
    
}

#pragma mark - Detail2ViewControllerDelegate methods
-(void)removeView
{
    WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    UIView* view = [appDelegate.window viewWithTag:999999];
    [view removeFromSuperview];
}


- (void)backClick
{
    WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    UIView* view = [appDelegate.window viewWithTag:999999];
    
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationDidStopSelector:@selector(removeView)];
    view.frame = CGRectMake(320, 20, 320, 460);
    view.alpha = 0.3;
    [UIView commitAnimations];
    
    
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    NSLog(@"add to refresh the data..");
    [super reloadTableViewDataSource];
    [self callNetAndCallBackIsNextPage:NO];
}
@end
